package service

import (
	"errors"
	"golang.org/x/net/context"
	"gopkg.in/olivere/elastic.v5"
	"log"
)
/*
1:docker es
docker run --restart=always -v /Users/didi/Code/Data/elasticData:/usr/share/elasticsearch/data -d --name es -p 8200:9200 -p 8300:9300 netroby/docker-elasticsearch elasticsearch
2:
*/

func ItemSaver(index string) (chan Item, error) {
	ch := make(chan Item, 1024)

	client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"),elastic.SetSniff(false))

	if err != nil {
		return nil, err
	}

	go func() {
		itemCount := 0
		for item := range ch {
			itemCount++
			log.Println("Item Saver: Got Item ", itemCount, item)
			err := Save(client, index, item)
			if err != nil {
				log.Printf("Item Saver: Save error: %s", err)
			}
		}
	}()
	return ch, nil
}

// 返回存储的ID
func Save(client *elastic.Client, index string, item Item) error {

	if item.Uri == "" {
		return errors.New("item.Uri 不能为空")
	}
	_, err := client.Index().
		Index(index).
		Type("doc").
		BodyJson(item).Do(context.Background())
	return err
}